﻿using JNPF.Basics.Logic.Common.Login;
using JNPF.Basics.Models;
using JNPF.Basics.Models.WorkFlow.Enums;
using JNPF.Basics.Models.WorkFlow.Model;
using JNPF.Utils;
using JNPF.Utils.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 流程任务
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-06-08 
    /// </summary>
    public class FlowTaskBll
    {
        private FlowTaskIService service = new FlowTaskService();
        private FlowEngineBll flowEngineBll = new FlowEngineBll();
        private FlowTaskNodeBll flowTaskNodeBll = new FlowTaskNodeBll();
        private FlowTaskOperatorBll flowTaskOperatorBll = new FlowTaskOperatorBll();
        private FlowTaskCirculateBll flowTaskCirculateBll = new FlowTaskCirculateBll();
        private FlowTaskOperatorRecordBll flowTaskOperatorRecordBll = new FlowTaskOperatorRecordBll();
        private OrganizeBll organizeBll = new OrganizeBll();
        private UserBll userBll = new UserBll();
        private MessageBll messageBll = new MessageBll();
        private FlowDelegateBll FlowDelegateBll = new FlowDelegateBll();
        private DictionaryDataBll dictionaryDataBll = new DictionaryDataBll();
        private PositionBll positionBll = new PositionBll();
        private DictionaryTypeBll dictionaryTypeBll = new DictionaryTypeBll();
        private DataInterfaceBll dataInterfaceBll = new DataInterfaceBll();
        private string taskNodeId = "taskNodeId";
        private string handleStatus = "handleStatus";


        /// <summary>
        /// 列表（流程监控）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<FlowTaskEntity>> GetMonitorList(PageInput input)
        {
            try
            {
                return await service.GetMonitorList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 列表（我发起的）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<FlowTaskEntity>> GetLaunchList(PageInput input)
        {
            try
            {
                var userId = UserProvider.Instance.Get().UserId;
                return await service.GetLaunchList(userId, input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 列表（待我审批）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<FlowTaskEntity>> GetWaitList(PageInput input)
        {
            try
            {
                var userId = UserProvider.Instance.Get().UserId;
                return await service.GetWaitList(userId, input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 列表（待我审批）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<FlowTaskEntity>> GetWaitList()
        {
            try
            {
                var userId = UserProvider.Instance.Get().UserId;
                var input = new PageInput();
                return await service.GetWaitList(userId, input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 列表（我已审批）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<FlowTaskEntity>> GetTrialList()
        {
            try
            {
                var userId = UserProvider.Instance.Get().UserId;
                var input = new PageInput();
                return await service.GetTrialList(userId, input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 列表（我已审批）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<FlowTaskEntity>> GetTrialList(PageInput input)
        {
            try
            {
                var userId = UserProvider.Instance.Get().UserId;
                return await service.GetTrialList(userId, input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 列表（抄送我的）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<FlowTaskEntity>> GetCirculateList(PageInput input)
        {
            try
            {
                var userId = UserProvider.Instance.Get().UserId;
                return await service.GetCirculateList(userId, input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 任务列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<List<FlowTaskEntity>> GetTaskList(string id)
        {
            try
            {
                return await service.GetTaskList(id);
            }
            catch (Exception ex)
            {

                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值、业务主键</param>
        /// <returns></returns>
        public async Task<FlowTaskEntity> GetInfo(string id)
        {
            try
            {
                return await service.GetInfo(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        public async Task Delete(FlowTaskEntity entity)
        {
            if (!CheckStatus(entity.Status))
                throw new Exception("当前流程正在运行不能删除");
            await service.Delete(entity);
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="flowId">流程主键</param>
        /// <param name="processId">实例Id</param>
        /// <param name="flowTitle">流程标题</param>
        /// <param name="flowUrgent">紧急程度</param>
        /// <param name="billNo">流水号</param>
        public async Task Save(string id, string flowId, string processId, string flowTitle, int? flowUrgent, string billNo, string formData,int type=0)
        {
            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    #region 创建实例
                    FlowEngineEntity flowEngineEntity = await flowEngineBll.GetInfo(flowId);
                    await service.Create(new FlowTaskEntity
                    {
                        Id = processId,
                        ProcessId = processId,
                        EnCode = billNo,
                        FullName = flowTitle,
                        FlowUrgent = flowUrgent,
                        FlowId = flowEngineEntity.Id,
                        FlowCode = flowEngineEntity.EnCode,
                        FlowName = flowEngineEntity.FullName,
                        FlowType = flowEngineEntity.Type,
                        FlowCategory = flowEngineEntity.Category,
                        FlowForm = flowEngineEntity.FormTemplateJson,
                        FlowFormContentJson = formData == null ? "" : formData,
                        FlowTemplateJson = flowEngineEntity.FlowTemplateJson,
                        FlowVersion = flowEngineEntity.Version,
                        Status = FlowTaskStatusEnum.Draft,
                        Completion = 0,
                        ThisStep = "开始",
                        CreatorTime = DateTime.Now,
                        CreatorUserId = UserProvider.Instance.Get().UserId
                    });
                    #endregion
                }
                else
                {
                    #region 更新实例
                    FlowTaskEntity flowTaskEntity = await GetInfo(processId);
                    if (!CheckStatus(flowTaskEntity.Status)&&type==0)
                        throw new Exception("当前流程正在运行不能重复保存");
                    if (type == 0)
                    {
                        flowTaskEntity.FullName = flowTitle;
                        flowTaskEntity.FlowUrgent = flowUrgent;
                    }
                    if (formData != null)
                    {
                        flowTaskEntity.FlowFormContentJson = formData;
                    }
                    await service.Update(flowTaskEntity);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public async Task Save(string id, string flowId, string processId, string flowTitle, int? flowUrgent, string billNo,int type=0)
        {
            try
            {
                await this.Save(id, flowId, processId, flowTitle, flowUrgent, billNo, null,type);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="flowId">流程主键</param>
        /// <param name="processId">流程主键</param>
        /// <param name="flowTitle">流程标题</param>
        /// <param name="flowUrgent">紧急程度</param>
        /// <param name="billNo">流水号</param>
        /// <param name="formEntity">表单对象</param>
        /// <param name="freeApproverUserId">授权审批人</param>
        public async Task Submit(string id, string flowId, string processId, string flowTitle, int? flowUrgent, string billNo, object formEntity, string freeApproverUserId = "")
        {
            try
            {
                var userInfo = UserProvider.Instance.Get();
                var userAllModel = await userBll.GetList();
                //流程引擎
                FlowEngineEntity flowEngineEntity = await flowEngineBll.GetInfo(flowId);
                //流程实例
                FlowTaskEntity flowTaskEntity = new FlowTaskEntity();
                //流程节点
                List<FlowTaskNodeEntity> flowTaskNodeEntityList = new List<FlowTaskNodeEntity>();
                //流程经办
                List<FlowTaskOperatorEntity> flowTaskOperatorEntityList = new List<FlowTaskOperatorEntity>();
                //流程传阅
                List<FlowTaskCirculateEntity> flowTaskCirculateEntityList = new List<FlowTaskCirculateEntity>();
                //判断字段类型
                Dictionary<string, string> jnpfKey = new Dictionary<string, string>();
                //下拉、单选、高级控件的list
                Dictionary<string, object> keyList = new Dictionary<string, object>();
                //自定义的可以获取到jnpfkey
                if (flowEngineEntity.FormType == 2)
                {
                    #region 将fields字段值序列化
                    var jobj = flowEngineEntity.FormTemplateJson.ToObject();
                    if (jobj != null)
                    {
                        jobj["fields"] = JsonHelper.ToJson(jobj["fields"]);
                    }
                    #endregion
                    FormDataModel formData = jobj.ToObject<FormDataModel>();
                    List<FieldsModel> fieLdsModelList = formData.fields.ToList<FieldsModel>();
                    await tempJson(fieLdsModelList, jnpfKey, keyList);
                }
                bool flag = string.IsNullOrEmpty(id);
                if (string.IsNullOrEmpty(id))
                {
                    #region 创建实例
                    flowTaskEntity.Id = processId;
                    flowTaskEntity.ProcessId = processId;
                    flowTaskEntity.EnCode = billNo;
                    flowTaskEntity.FullName = flowTitle;
                    flowTaskEntity.FlowUrgent = flowUrgent;
                    flowTaskEntity.FlowId = flowEngineEntity.Id;
                    flowTaskEntity.FlowCode = flowEngineEntity.EnCode;
                    flowTaskEntity.FlowName = flowEngineEntity.FullName;
                    flowTaskEntity.FlowType = flowEngineEntity.Type;
                    flowTaskEntity.FlowCategory = flowEngineEntity.Category;
                    flowTaskEntity.FlowForm = flowEngineEntity.FormTemplateJson;
                    flowTaskEntity.FlowTemplateJson = flowEngineEntity.FlowTemplateJson;
                    flowTaskEntity.FlowVersion = flowEngineEntity.Version;
                    flowTaskEntity.Status = FlowTaskStatusEnum.Handle;
                    flowTaskEntity.Completion = 0;
                    flowTaskEntity.EnabledMark = FlowTaskStatusEnum.Handle;
                    flowTaskEntity.StartTime = DateTime.Now;
                    flowTaskEntity.CreatorTime = DateTime.Now;
                    flowTaskEntity.CreatorUserId = userInfo.UserId;
                    if (formEntity != null)
                        flowTaskEntity.FlowFormContentJson = formEntity.ToJson();
                    #endregion
                }
                else
                {
                    #region 更新实例
                    flowTaskEntity = await GetInfo(id);
                    if (!CheckStatus(flowTaskEntity.Status))
                        throw new Exception("当前流程正在运行不能重复提交");
                    flowTaskEntity.FullName = flowTitle;
                    flowTaskEntity.FlowUrgent = flowUrgent;
                    flowTaskEntity.Status = FlowTaskStatusEnum.Handle;
                    flowTaskEntity.StartTime = DateTime.Now;
                    flowTaskEntity.FlowTemplateJson = flowEngineEntity.FlowTemplateJson;
                    flowTaskEntity.LastModifyTime = DateTime.Now;
                    flowTaskEntity.LastModifyUserId = userInfo.UserId;
                    if (formEntity != null)
                        flowTaskEntity.FlowFormContentJson = formEntity.ToJson();
                    await service.Update(flowTaskEntity);
                    #endregion
                }

                //流程表单Json
                var formDataJson = flowTaskEntity.FlowTemplateJson;
                ChildNodeModel childNodeModel = formDataJson.ToObject<ChildNodeModel>();
                //获取流程节点
                List<ChildNodeModelList> childNodeList = new List<ChildNodeModelList>();
                List<ConditionList> conditionList = new List<ConditionList>();
                //递归获取条件数据和节点数据
                childNodeModelLists(childNodeModel, childNodeList, conditionList);
                ChildNodeModelList start = new ChildNodeModelList();

                //创建节点
                var emptyList = new List<FlowTaskNodeEntity>();
                var timerList = new List<FlowTaskNodeEntity>();
                foreach (var modelList in childNodeList)
                {
                    var flowTaskNodeEntity = new FlowTaskNodeEntity();
                    flowTaskNodeEntity.Id = CommonHelper.Guid;
                    modelList.taskNodeId = flowTaskNodeEntity.Id;
                    modelList.taskId = flowTaskEntity.Id;
                    flowTaskNodeEntity.CreatorTime = DateTime.Now;
                    flowTaskNodeEntity.TaskId = flowTaskEntity.Id;
                    flowTaskNodeEntity.NodeCode = modelList.nodeId;
                    flowTaskNodeEntity.NodeName = modelList.title;
                    flowTaskNodeEntity.NodeType = modelList.type;
                    flowTaskNodeEntity.NodeUp = modelList.rejectStep;
                    flowTaskNodeEntity.NodeNext = this.GetNextNode(flowTaskEntity.FlowFormContentJson, conditionList, childNodeList, modelList, jnpfKey, keyList);
                    flowTaskNodeEntity.NodePropertyJson = modelList.ToJson();
                    flowTaskNodeEntity.Completion = modelList.type == "start" ? 1 : 0;
                    if (modelList.type == "start")
                    {
                        //开始节点赋空值
                        modelList.approverPos = new List<string>();
                        modelList.approvers = new List<string>();
                        modelList.circulatePosition = new List<string>();
                        modelList.circulateUser = new List<string>();
                        start = modelList;
                        flowTaskNodeEntity.NodeName = "开始";
                        flowTaskNodeEntity.NodePropertyJson = modelList.ToJson();
                    }
                    flowTaskNodeEntityList.Add(flowTaskNodeEntity);
                    if ("empty".Equals(modelList.type))
                    {
                        emptyList.Add(flowTaskNodeEntity);
                    }
                    if ("timer".Equals(modelList.type))
                    {
                        timerList.Add(flowTaskNodeEntity);
                    }
                }
                //指向empty，继续指向下一个节点
                foreach (var empty in emptyList)
                {
                    var noxtEmptyList = flowTaskNodeEntityList.FindAll(f => f.NodeNext.Equals(empty.NodeCode));
                    foreach (var entity in noxtEmptyList)
                    {
                        entity.NodeNext = empty.NodeNext;
                    }
                }

                await flowTaskNodeBll.Create(flowTaskNodeEntityList);
                //更新流程任务
                if (flag)
                {
                    await service.Create(flowTaskEntity);
                }
                else
                {
                    await service.Update(flowTaskEntity);
                }
                #region 创建经办
                //获取下一个节点
                var startNode = flowTaskNodeEntityList.Find(m => m.NodeType == "start").MapTo<FlowTaskNodeEntity>();
                string fNodeNext = "";
                if (startNode != null)
                {
                    fNodeNext = startNode.NodeNext.IsNotEmptyOrNull() ? startNode.NodeNext : "";
                }
                var nextNodeModel = childNodeList.Find(c => c.nodeId == fNodeNext);
                if (nextNodeModel != null)
                {
                    //发起者主管
                    if (nextNodeModel.assigneeType.Equals((int)FlowTaskOperatorEnum.LaunchCharge))
                    {
                        if (string.IsNullOrEmpty(userInfo.ManagerId))
                        {
                            await service.Delete(flowTaskEntity);
                            await service.Create(flowTaskEntity);
                            throw new Exception("没有找到发起者主管");
                        }
                        flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                        {
                            Id = CommonHelper.Guid,
                            HandleType = ((int)FlowTaskOperatorEnum.LaunchCharge).ToString(),
                            HandleId = userInfo.ManagerId,
                            NodeCode = nextNodeModel.nodeId,
                            NodeName = nextNodeModel.title,
                            TaskNodeId = nextNodeModel.taskNodeId,
                            TaskId = nextNodeModel.taskId,
                            CreatorTime = DateTime.Now,
                            Completion = 0,
                            State = "0",
                            Type = nextNodeModel.assigneeType.ToString()
                        });
                    }
                    //发起者部门主管
                    if (nextNodeModel.assigneeType.Equals((int)FlowTaskOperatorEnum.DepartmentCharge))
                    {
                        var organizeEntity = await organizeBll.GetInfo(userInfo.OrganizeId);
                        if (string.IsNullOrEmpty(organizeEntity.ManagerId))
                        {
                            await service.Delete(flowTaskEntity);
                            await service.Create(flowTaskEntity);
                            throw new Exception("没有找到部门主管");
                        }
                        flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                        {
                            Id = CommonHelper.Guid,
                            HandleType = ((int)FlowTaskOperatorEnum.DepartmentCharge).ToString(),
                            HandleId = organizeEntity.ManagerId,
                            NodeCode = nextNodeModel.nodeId,
                            NodeName = nextNodeModel.title,
                            TaskNodeId = nextNodeModel.taskNodeId,
                            TaskId = nextNodeModel.taskId,
                            CreatorTime = DateTime.Now,
                            Completion = 0,
                            State = "0",
                            Type = nextNodeModel.assigneeType.ToString()
                        });
                    }
                    //发起者本人
                    if (nextNodeModel.assigneeType.Equals((int)FlowTaskOperatorEnum.InitiatorMe))
                    {
                        flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                        {
                            Id = CommonHelper.Guid,
                            HandleType = ((int)FlowTaskOperatorEnum.DepartmentCharge).ToString(),
                            HandleId = flowTaskEntity.CreatorUserId,
                            NodeCode = nextNodeModel.nodeId,
                            NodeName = nextNodeModel.title,
                            TaskNodeId = nextNodeModel.taskNodeId,
                            TaskId = nextNodeModel.taskId,
                            CreatorTime = DateTime.Now,
                            Completion = 0,
                            State = "0",
                            Type = nextNodeModel.assigneeType.ToString()
                        });
                    }

                    //授权审批人
                    if (nextNodeModel.assigneeType.Equals((int)FlowTaskOperatorEnum.FreeApprover))
                    {
                        if (string.IsNullOrEmpty(freeApproverUserId)) {
                            
                        }
                        flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                        {
                            Id = CommonHelper.Guid,
                            HandleType = ((int)FlowTaskOperatorEnum.FreeApprover).ToString(),
                            HandleId = freeApproverUserId,
                            NodeCode = nextNodeModel.nodeId,
                            NodeName = nextNodeModel.title,
                            TaskNodeId = nextNodeModel.taskNodeId,
                            TaskId = nextNodeModel.taskId,
                            CreatorTime = DateTime.Now,
                            Completion = 0,
                            State = "0",
                            Type = nextNodeModel.assigneeType.ToString()
                        });
                    }
                    //发起者【指定用户】
                    if (nextNodeModel.approverPos != null)
                    {
                        foreach (var userId in nextNodeModel.approvers)
                        {
                            flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                            {
                                Id = CommonHelper.Guid,
                                HandleType = ((int)FlowTaskOperatorEnum.AppointUser).ToString(),
                                HandleId = userId,
                                NodeCode = nextNodeModel.nodeId,
                                NodeName = nextNodeModel.title,
                                TaskNodeId = nextNodeModel.taskNodeId,
                                TaskId = nextNodeModel.taskId,
                                CreatorTime = DateTime.Now,
                                Completion = 0,
                                State = "0",
                                Type = nextNodeModel.assigneeType.ToString()
                            });
                        }
                    }
                    //发起者【指定岗位】
                    if (nextNodeModel.approverPos != null)
                    {
                        foreach (var positionId in nextNodeModel.approverPos)
                        {
                            var userPosition = userAllModel.FindAll(x => x.PositionId.Contains(positionId)).Select(x => x.Id).ToList<string>();
                            getApproverUser(userPosition, flowTaskOperatorEntityList, nextNodeModel);
                        }
                    }

                    await flowTaskOperatorBll.Create(flowTaskOperatorEntityList);
                    #endregion

                    #region 创建传阅
                    //得到【指定用户】
                    if (nextNodeModel.circulateUser != null)
                    {
                        foreach (var userId in nextNodeModel.circulateUser)
                        {
                            // 用户岗位
                            List<string> positionIds = userAllModel.FindAll(x => x.Id.Contains(userId)).Select(s => s.PositionId).ToList();
                            if (getCirculateUser(nextNodeModel.circulatePosition, positionIds))
                            {
                                flowTaskCirculateEntityList.Add(new FlowTaskCirculateEntity()
                                {
                                    Id = CommonHelper.Guid,
                                    ObjectType = ((int)FlowTaskOperatorEnum.AppointUser).ToString(),
                                    ObjectId = userId,
                                    NodeCode = nextNodeModel.nodeId,
                                    NodeName = nextNodeModel.title,
                                    TaskNodeId = nextNodeModel.taskNodeId,
                                    TaskId = nextNodeModel.taskId,
                                    CreatorTime = DateTime.Now,
                                });
                            }
                        }
                    }
                    //得到【指定岗位】
                    if (nextNodeModel.circulatePosition != null)
                    {
                        foreach (var positionId in nextNodeModel.circulatePosition)
                        {
                            flowTaskCirculateEntityList.Add(new FlowTaskCirculateEntity()
                            {
                                Id = CommonHelper.Guid,
                                ObjectType = ((int)FlowTaskOperatorEnum.AppointPosition).ToString(),
                                ObjectId = positionId,
                                NodeCode = nextNodeModel.nodeId,
                                NodeName = nextNodeModel.title,
                                TaskNodeId = nextNodeModel.taskNodeId,
                                TaskId = nextNodeModel.taskId,
                                CreatorTime = DateTime.Now
                            });
                        }
                    }
                    await flowTaskCirculateBll.Create(flowTaskCirculateEntityList);
                    #endregion

                    #region 更新实例
                    flowTaskEntity.ThisStepId = nextNodeModel.nodeId;
                    flowTaskEntity.ThisStep = nextNodeModel.title;
                    flowTaskEntity.Completion = nextNodeModel.progress.ToInt();
                    await service.Update(flowTaskEntity);
                    #endregion
                }
                #region 提交记录
                FlowTaskOperatorRecordEntity flowTaskOperatorRecordEntity = new FlowTaskOperatorRecordEntity();
                flowTaskOperatorRecordEntity.HandleId = userInfo.UserId;
                flowTaskOperatorRecordEntity.HandleTime = DateTime.Now;
                flowTaskOperatorRecordEntity.HandleStatus = 2;
                flowTaskOperatorRecordEntity.NodeName = "开始";
                flowTaskOperatorRecordEntity.TaskId = flowTaskEntity.Id;
                await flowTaskOperatorRecordBll.Create(flowTaskOperatorRecordEntity);
                #endregion

                #region 开始事件
                if (start.hasInitfunc)
                {
                    string faceUrl = start.initInterfaceUrl + "?" + taskNodeId + "=" + startNode.Id;
                    if (start.initInterfaceUrl.Contains("https"))
                    {
                        WebHelper.HttpWebRequest(faceUrl);
                    }
                    else
                    {
                        WebHelper.HttpWebRequest(faceUrl);
                    }
                }
                #endregion

                #region 消息提醒
                Dictionary<string, object> message = new Dictionary<string, object>();
                message["type"] = FlowMessageEnum.wait;
                message["id"] = processId;
                //审核提醒
                await MessagePush(flowTaskOperatorEntityList, flowTitle + "【审核】", message.ToJson());
                //抄送提醒
                message["type"] = FlowMessageEnum.circulate;
                await MessagePushCirculate(flowTaskCirculateEntityList, flowTaskEntity.FullName + "【抄送】", message.ToJson());
                #endregion

            }
            catch (Exception ex)
            {
                LogFactory.GetLogger().Error("FlowTaskBll日志：" + ex);
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="processId">业务主键</param>
        /// <param name="flowId">流程主键</param>
        /// <param name="flowTitle">流程标题</param>
        /// <param name="flowUrgent">紧急程度</param>
        /// <param name="billNo">流水号</param>
        /// <param name="formEntity">表单对象</param>
        /// <param name="freeApproverUserId">授权审批人</param>
        public async Task Submit(string processId, string flowId, string flowTitle, int? flowUrgent, string billNo, object formEntity, string freeApproverUserId = "")
        {
            var flowTaskEntity = await this.GetInfo(processId);
            if (flowTaskEntity != null)
            {
                await this.Submit(flowTaskEntity.Id, flowId, processId, flowTitle, flowUrgent, billNo, formEntity, freeApproverUserId);
            }
            else
            {
                await this.Submit("", flowId, processId, flowTitle, flowUrgent, billNo, formEntity, freeApproverUserId);
            }
        }
        /// <summary>
        /// 撤回
        /// </summary>
        /// <param name="flowTaskEntity">流程实例</param>
        /// <param name="flowHandleModel">流程经办</param>
        public async Task Revoke(FlowTaskEntity flowTaskEntity, string flowHandleModel)
        {
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    #region 撤回数据
                    //删除节点
                    await flowTaskNodeBll.DeleteByTaskId(flowTaskEntity.Id);
                    //删除经办
                    await flowTaskOperatorBll.DeleteByTaskId(flowTaskEntity.Id);
                    //删除传阅
                    await flowTaskCirculateBll.DeleteByTaskId(flowTaskEntity.Id);
                    #endregion

                    #region 更新实例
                    flowTaskEntity.ThisStepId = "";
                    flowTaskEntity.ThisStep = "开始";
                    flowTaskEntity.Completion = 0;
                    flowTaskEntity.Status = FlowTaskStatusEnum.Revoke;
                    flowTaskEntity.StartTime = null;
                    flowTaskEntity.EndTime = null;
                    await service.Update(flowTaskEntity);
                    #endregion

                    #region 撤回记录
                    var userInfo = UserProvider.Instance.Get();
                    FlowTaskOperatorRecordEntity flowTaskOperatorRecordEntity = new FlowTaskOperatorRecordEntity();
                    flowTaskOperatorRecordEntity.HandleOpinion = flowHandleModel;
                    flowTaskOperatorRecordEntity.HandleId = userInfo.UserId;
                    flowTaskOperatorRecordEntity.HandleTime = DateTime.Now;
                    flowTaskOperatorRecordEntity.HandleStatus = 3;
                    flowTaskOperatorRecordEntity.NodeName = "开始";
                    flowTaskOperatorRecordEntity.TaskId = flowTaskEntity.Id;
                    await flowTaskOperatorRecordBll.Create(flowTaskOperatorRecordEntity);
                    #endregion

                    scope.Complete();

                }
            }
            catch (TransactionAbortedException ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="flowTaskEntity">流程实例</param>
        /// <param name="flowTaskOperatorEntity">流程经办</param>
        /// <param name="flowHandleModel">流程经办</param>
        /// <param name="freeApproverUserId">授权审批人</param>
        public async Task Audit(FlowTaskEntity flowTaskEntity, FlowTaskOperatorEntity flowTaskOperatorEntity, FlowHandleModel flowHandleModel, string freeApproverUserId)
        {
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    var userAllModel = await userBll.GetList();
                    var userInfo = UserProvider.Instance.Get();
                    //流程节点
                    List<FlowTaskNodeEntity> flowTaskNodeEntityList = (await flowTaskNodeBll.GetList(flowTaskEntity.Id)).FindAll(x => x.State == "0");
                    //当前节点
                    FlowTaskNodeEntity flowTaskNodeEntity = flowTaskNodeEntityList.Find(m => m.Id == flowTaskOperatorEntity.TaskNodeId);
                    //当前节点属性
                    ChildNodeModelList nodeModel = flowTaskNodeEntity.NodePropertyJson.ToObject<ChildNodeModelList>();
                    //当前节点所有经办人
                    var entityList = (await flowTaskOperatorBll.GetList(flowTaskNodeEntity.TaskId)).FindAll(x => x.State == "0");
                    List<FlowTaskOperatorEntity> thisFlowTaskOperatorEntityList = entityList.FindAll(m => m.TaskNodeId == flowTaskNodeEntity.Id);
                    //下个节点
                    FlowTaskNodeEntity nextNodeEntity = flowTaskNodeEntityList.Find(m => m.NodeCode == flowTaskNodeEntity.NodeNext);
                    //下个节点属性
                    ChildNodeModelList nextNodeModel = nextNodeEntity.NodePropertyJson.ToObject<ChildNodeModelList>();
                    var isUpdateNextflowTaskNode = false;
                    FlowTaskNodeEntity nextFreeTaskNode = null;
                    //判断当前节点是否是加签
                    if (!string.IsNullOrEmpty(freeApproverUserId))
                    {
                        //当前是加签,设置当前的节点和属性
                        if (nodeModel.assigneeType == (int)FlowTaskOperatorEnum.FreeApprover)
                        {
                            nextNodeModel = nodeModel;
                            nextNodeEntity = flowTaskNodeEntity;
                        }
                    }
                    else
                    {
                        //判断下一个节点是否加签,跳过继续下一节点
                        if (nextNodeModel.assigneeType == (int)FlowTaskOperatorEnum.FreeApprover)
                        {
                            isUpdateNextflowTaskNode = true;
                            //赋值加签节点
                            nextFreeTaskNode = nextNodeEntity;
                            var nextId = nextNodeEntity.NodeNext;
                            //获取加签下一节点
                            nextNodeEntity = flowTaskNodeEntityList.Find(x => x.NodeCode == nextId);
                            nextNodeModel = nextNodeEntity.NodePropertyJson.ToObject<ChildNodeModelList>();
                        }
                    }
                    #region 审核记录
                    FlowTaskOperatorRecordEntity flowTaskOperatorRecordEntity = new FlowTaskOperatorRecordEntity();
                    flowTaskOperatorRecordEntity.HandleOpinion = flowHandleModel.handleOpinion;
                    flowTaskOperatorRecordEntity.HandleId = userInfo.UserId;
                    flowTaskOperatorRecordEntity.HandleTime = DateTime.Now;
                    flowTaskOperatorRecordEntity.HandleStatus = 1;
                    flowTaskOperatorRecordEntity.NodeCode = flowTaskNodeEntity.NodeCode;
                    flowTaskOperatorRecordEntity.NodeName = flowTaskNodeEntity.NodeName;
                    flowTaskOperatorRecordEntity.TaskOperatorId = flowTaskOperatorEntity.Id;
                    flowTaskOperatorRecordEntity.TaskNodeId = flowTaskNodeEntity.Id;
                    flowTaskOperatorRecordEntity.TaskId = flowTaskEntity.Id;
                    await flowTaskOperatorRecordBll.Create(flowTaskOperatorRecordEntity);
                    #endregion
                    //更新或签都改成完成
                    if (nodeModel.assigneeType == (int)FlowTaskOperatorEnum.FixedApprover)
                    {
                        await UpdateReject(flowTaskEntity.Id, ((int)FlowTaskOperatorEnum.FixedApprover).ToString());
                    }
                    #region 更新经办
                    //if (nodeModel.assigneeType == (int)FlowTaskOperatorEnum.FixedJointlyApprover)
                    //{
                    //    flowTaskOperatorEntity = thisFlowTaskOperatorEntityList.Find(t => t.Id == flowHandleModel.delegateId);
                    //}
                    flowTaskOperatorEntity.Completion = 1;
                    flowTaskOperatorEntity.HandleStatus = 1;
                    flowTaskOperatorEntity.HandleTime = DateTime.Now;
                    await flowTaskOperatorBll.Update(flowTaskOperatorEntity);
                    //更新委托人的经办
                    //if (nodeModel.assigneeType == (int)FlowTaskOperatorEnum.FixedJointlyApprover)
                    //{
                    //    //获取委托人的id
                    //    List<string> userId = await FlowDelegateBll.GetUser(userInfo.UserId);
                    //    await flowTaskOperatorBll.UpdateCompletion(flowTaskEntity.Id, userId);
                    //}
                    #endregion

                    #region 更新节点
                    var isUpdateflowTaskNode = true;
                    var isCompletionFixedJointlyApprover = true;
                    if (nodeModel.assigneeType == (int)FlowTaskOperatorEnum.FreeApprover && !string.IsNullOrEmpty(freeApproverUserId))
                    {
                        isUpdateflowTaskNode = false;
                    }
                    else if (nodeModel.assigneeType == (int)FlowTaskOperatorEnum.FixedJointlyApprover && thisFlowTaskOperatorEntityList.FindAll(t => t.HandleId != userInfo.UserId && t.Completion == 0).Count > 0)
                    {
                        isUpdateflowTaskNode = false;
                        isCompletionFixedJointlyApprover = false;
                    }

                    if (isUpdateflowTaskNode)
                    {
                        flowTaskNodeEntity.Completion = 1;
                        await flowTaskNodeBll.Update(flowTaskNodeEntity);
                        //判断是否跳过加签流程,更新跳过加签流程
                        if (isUpdateNextflowTaskNode)
                        {
                            nextFreeTaskNode.Completion = 1;
                            await flowTaskNodeBll.Update(nextFreeTaskNode);
                        }
                    }
                    #endregion

                    //流程经办
                    List<FlowTaskOperatorEntity> flowTaskOperatorEntityList = new List<FlowTaskOperatorEntity>();
                    //流程传阅
                    List<FlowTaskCirculateEntity> flowTaskCirculateEntityList = new List<FlowTaskCirculateEntity>();

                    #region 更新实例
                    if (flowTaskNodeEntity.Completion > 0)
                    {
                        //节点事件
                        if (nodeModel.hasApproverfunc)
                        {
                            string faceUrl = nodeModel.approverInterfaceUrl + "?" + taskNodeId + "=" + flowTaskNodeEntity.Id + "&" + handleStatus + "=" + flowTaskOperatorRecordEntity.HandleStatus;

                            if (nodeModel.approverInterfaceUrl.Contains("https"))
                            {
                                WebHelper.HttpWebRequest(faceUrl);
                            }
                            else
                            {
                                WebHelper.HttpWebRequest(faceUrl);
                            }
                        }
                        flowTaskEntity.ThisStepId = nextNodeEntity.NodeCode;
                        flowTaskEntity.ThisStep = nextNodeEntity.NodeName;
                        flowTaskEntity.Completion = nextNodeModel.progress.ToInt();
                        //判断是否结束流程【正常通过】
                        if (nextNodeEntity.NodeType == "endround")
                        {
                            flowTaskEntity.Status = FlowTaskStatusEnum.Adopt;
                            flowTaskEntity.Completion = 100;
                            flowTaskEntity.EndTime = DateTime.Now;
                            flowTaskEntity.ThisStepId = "";
                            #region 流程完成通知发起人
                            var strPraseJson = JsonHelper.PraseToJson(flowTaskEntity.FlowFormContentJson);
                            await messageBll.SentMessage(new List<string>() { flowTaskEntity.CreatorUserId }, flowTaskEntity.FullName + "【审核】", "审批通过");
                            #endregion
                            //结束事件
                            if (nextNodeModel.hasEndfunc)
                            {
                                string faceUrl = nextNodeModel.endInterfaceUrl + "?" + taskNodeId + "=" + nextNodeEntity.Id;
                                if (nextNodeModel.endInterfaceUrl.Contains("https"))
                                {
                                    WebHelper.HttpWebRequest(faceUrl);
                                }
                                else
                                {
                                    WebHelper.HttpWebRequest(faceUrl);
                                }
                            }
                        }
                        await service.Update(flowTaskEntity);
                    }
                    #endregion

                    #region 创建经办
                    var createUser = userAllModel.Find(x => x.Id.Equals(flowTaskEntity.CreatorUserId));
                    //发起者【发起主管】
                    if (nextNodeModel.assigneeType == (int)FlowTaskOperatorEnum.LaunchCharge)
                    {
                        flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                        {
                            Id = CommonHelper.Guid,
                            HandleType = ((int)FlowTaskOperatorEnum.LaunchCharge).ToString(),
                            HandleId = createUser.ManagerId,
                            NodeCode = nextNodeModel.nodeId,
                            NodeName = nextNodeModel.title,
                            TaskNodeId = nextNodeModel.taskNodeId,
                            TaskId = nextNodeModel.taskId,
                            CreatorTime = DateTime.Now,
                            Completion = 0,
                            State = "0",
                            Type = nextNodeModel.assigneeType.ToString()
                        });
                    }
                    //发起者【部门主管】
                    if (nextNodeModel.assigneeType == (int)FlowTaskOperatorEnum.DepartmentCharge)
                    {
                        var organizeEntity = await organizeBll.GetInfo(createUser.OrganizeId);
                        flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                        {
                            Id = CommonHelper.Guid,
                            HandleType = ((int)FlowTaskOperatorEnum.DepartmentCharge).ToString(),
                            HandleId = organizeEntity.ManagerId,
                            NodeCode = nextNodeModel.nodeId,
                            NodeName = nextNodeModel.title,
                            TaskNodeId = nextNodeModel.taskNodeId,
                            TaskId = nextNodeModel.taskId,
                            CreatorTime = DateTime.Now,
                            Completion = 0,
                            State = "0",
                            Type = nextNodeModel.assigneeType.ToString()
                        });
                    }
                    //发起者【发起本人】
                    if (nextNodeModel.assigneeType == (int)FlowTaskOperatorEnum.InitiatorMe)
                    {
                        flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                        {
                            Id = CommonHelper.Guid,
                            HandleType = ((int)FlowTaskOperatorEnum.InitiatorMe).ToString(),
                            HandleId = flowTaskEntity.CreatorUserId,
                            NodeCode = nextNodeModel.nodeId,
                            NodeName = nextNodeModel.title,
                            TaskNodeId = nextNodeModel.taskNodeId,
                            TaskId = nextNodeModel.taskId,
                            CreatorTime = DateTime.Now,
                            Completion = 0,
                            State = "0",
                            Type = nextNodeModel.assigneeType.ToString()
                        });
                    }
                    //得到【授权审批人】
                    if (nextNodeModel.assigneeType == (int)FlowTaskOperatorEnum.FreeApprover)
                    {
                        if (string.IsNullOrEmpty(freeApproverUserId))
                            throw new Exception("未找到授权审批人");
                        flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                        {
                            Id = CommonHelper.Guid,
                            HandleType = ((int)FlowTaskOperatorEnum.FreeApprover).ToString(),
                            HandleId = freeApproverUserId,
                            NodeCode = nextNodeModel.nodeId,
                            NodeName = nextNodeModel.title,
                            TaskNodeId = nextNodeModel.taskNodeId,
                            TaskId = nextNodeModel.taskId,
                            CreatorTime = DateTime.Now,
                            Completion = 0,
                            State = "0",
                            Type = nextNodeModel.assigneeType.ToString()
                        });
                    }
                    //得到【指定用户】
                    if (nextNodeModel.approvers != null)
                    {
                        foreach (var userId in nextNodeModel.approvers)
                        {
                            flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                            {
                                Id = CommonHelper.Guid,
                                HandleType = ((int)FlowTaskOperatorEnum.AppointUser).ToString(),
                                HandleId = userId,
                                NodeCode = nextNodeModel.nodeId,
                                NodeName = nextNodeModel.title,
                                TaskNodeId = nextNodeModel.taskNodeId,
                                TaskId = nextNodeModel.taskId,
                                CreatorTime = DateTime.Now,
                                Completion = 0,
                                State = "0",
                                Type = nextNodeModel.assigneeType.ToString()
                            });
                        }
                    }
                    //得到【指定岗位】
                    if (nextNodeModel.approverPos != null)
                    {
                        foreach (var positionId in nextNodeModel.approverPos)
                        {
                            var userPosition = userAllModel.FindAll(x => x.PositionId.Contains(positionId)).Select(x => x.Id).ToList<string>();
                            getApproverUser(userPosition, flowTaskOperatorEntityList, nextNodeModel);
                        }
                    }
                    if (isCompletionFixedJointlyApprover)
                    {
                        await flowTaskOperatorBll.Create(flowTaskOperatorEntityList);
                    }

                    #endregion

                    #region 创建传阅
                    if (flowTaskNodeEntity.Completion > 0)
                    {
                        //得到【指定用户】
                        if (nextNodeModel.circulateUser != null)
                        {
                            foreach (var userId in nextNodeModel.circulateUser)
                            {
                                // 用户岗位
                                List<string> positionIds = userAllModel.FindAll(x => x.Id.Contains(userId)).Select(s => s.PositionId).ToList();
                                if (getCirculateUser(nextNodeModel.circulatePosition, positionIds))
                                {
                                    flowTaskCirculateEntityList.Add(new FlowTaskCirculateEntity()
                                    {
                                        Id = CommonHelper.Guid,
                                        ObjectType = ((int)FlowTaskOperatorEnum.AppointUser).ToString(),
                                        ObjectId = userId,
                                        NodeCode = nextNodeModel.nodeId,
                                        NodeName = nextNodeModel.title,
                                        TaskNodeId = nextNodeModel.taskNodeId,
                                        TaskId = nextNodeModel.taskId,
                                        CreatorTime = DateTime.Now
                                    });
                                }

                            }
                        }
                        //得到【指定岗位】
                        if (nextNodeModel.circulatePosition != null)
                        {
                            foreach (var positionId in nextNodeModel.circulatePosition)
                            {
                                flowTaskCirculateEntityList.Add(new FlowTaskCirculateEntity()
                                {
                                    Id = CommonHelper.Guid,
                                    ObjectType = ((int)FlowTaskOperatorEnum.AppointPosition).ToString(),
                                    ObjectId = positionId,
                                    NodeCode = nextNodeModel.nodeId,
                                    NodeName = nextNodeModel.title,
                                    TaskNodeId = nextNodeModel.taskNodeId,
                                    TaskId = nextNodeModel.taskId,
                                    CreatorTime = DateTime.Now
                                });
                            }
                        }
                        await flowTaskCirculateBll.Create(flowTaskCirculateEntityList);
                    }
                    #endregion

                    #region 消息提醒
                    if (flowTaskNodeEntity.Completion > 0)
                    {
                        Dictionary<string, object> message = new Dictionary<string, object>();
                        message["type"] = FlowMessageEnum.wait;
                        message["id"] = flowTaskEntity.Id;
                        //审核提醒
                        await MessagePush(flowTaskOperatorEntityList, flowTaskEntity.FullName + "【审核】", message.ToJson());
                        //抄送提醒
                        message["type"] = FlowMessageEnum.circulate;
                        await MessagePushCirculate(flowTaskCirculateEntityList, flowTaskEntity.FullName + "【抄送】", message.ToJson());
                        //创建者消息提醒
                        List<string> userId = new List<string>();
                        userId.Add(flowTaskEntity.CreatorUserId);
                        message["type"] = FlowMessageEnum.me;
                        await messageBll.SentMessage(userId, flowTaskEntity.FullName + "【审核通过】", message.ToJson());
                    }
                    #endregion

                    scope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 驳回
        /// </summary>
        /// <param name="flowTaskEntity">流程实例</param>
        /// <param name="flowTaskOperatorRecordEntity">流程经办</param>
        /// <param name="flowHandleModel">流程经办</param>
        public async Task Reject(FlowTaskEntity flowTaskEntity, FlowTaskOperatorEntity flowTaskOperatorEntity, FlowHandleModel flowHandleModel)
        {
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    var userAllModel = await userBll.GetList();
                    var userInfo = UserProvider.Instance.Get();
                    //流程节点
                    List<FlowTaskNodeEntity> flowTaskNodeEntityList = (await flowTaskNodeBll.GetList(flowTaskEntity.Id)).FindAll(x => x.State.Equals("0"));
                    //当前节点
                    FlowTaskNodeEntity flowTaskNodeEntity = flowTaskNodeEntityList.Find(m => m.Id == flowTaskOperatorEntity.TaskNodeId);
                    //当前节点属性
                    ChildNodeModelList nodeModel = flowTaskNodeEntity.NodePropertyJson.ToObject<ChildNodeModelList>();
                    //当前节点经办
                    List<FlowTaskOperatorEntity> thisFlowTaskOperatorEntityList = (await flowTaskOperatorBll.GetList(flowTaskNodeEntity.TaskId)).FindAll(m => m.State.Equals("0"));
                    //上个节点
                    FlowTaskNodeEntity upNodeEntity = flowTaskNodeEntityList.Find(m => m.NodeNext == flowTaskNodeEntity.NodeCode);
                    //上个节点属性
                    ChildNodeModelList upNodeModel = upNodeEntity == null ? null : upNodeEntity.NodePropertyJson.ToObject<ChildNodeModelList>();
                    //流程经办
                    List<FlowTaskOperatorEntity> flowTaskOperatorEntityList = new List<FlowTaskOperatorEntity>();

                    #region 驳回记录
                    FlowTaskOperatorRecordEntity flowTaskOperatorRecordEntity = new FlowTaskOperatorRecordEntity();
                    flowTaskOperatorRecordEntity.HandleOpinion = flowHandleModel.handleOpinion;
                    flowTaskOperatorRecordEntity.HandleId = userInfo.UserId;
                    flowTaskOperatorRecordEntity.HandleTime = DateTime.Now;
                    flowTaskOperatorRecordEntity.HandleStatus = 0;
                    flowTaskOperatorRecordEntity.NodeCode = flowTaskNodeEntity.NodeCode;
                    flowTaskOperatorRecordEntity.NodeName = flowTaskNodeEntity.NodeName;
                    flowTaskOperatorRecordEntity.TaskOperatorId = flowTaskOperatorEntity.Id;
                    flowTaskOperatorRecordEntity.TaskNodeId = flowTaskNodeEntity.Id;
                    flowTaskOperatorRecordEntity.TaskId = flowTaskEntity.Id;
                    await flowTaskOperatorRecordBll.Create(flowTaskOperatorRecordEntity);
                    #endregion
                    //更新或签都改成驳回
                    if (nodeModel.assigneeType == (int)FlowTaskOperatorEnum.FixedApprover)
                    {
                        await UpdateReject(flowTaskEntity.Id, ((int)FlowTaskOperatorEnum.FixedApprover).ToString());
                    }
                    //更新会签都改成驳回
                    if (nodeModel.assigneeType == (int)FlowTaskOperatorEnum.FixedJointlyApprover)
                    {
                        await UpdateReject(flowTaskEntity.Id, ((int)FlowTaskOperatorEnum.FixedJointlyApprover).ToString());
                    }
                    // 更新经办
                    if (nodeModel.assigneeType == (int)FlowTaskOperatorEnum.FixedJointlyApprover)
                    {
                        flowTaskOperatorEntity = thisFlowTaskOperatorEntityList.Find(x => x.HandleId == userInfo.UserId);
                    }

                    #region 更新经办
                    if (nodeModel.assigneeType == (int)FlowTaskOperatorEnum.FixedJointlyApprover)
                    {
                        flowTaskOperatorEntity = thisFlowTaskOperatorEntityList.Find(t => t.HandleId == userInfo.UserId);
                    }
                    flowTaskOperatorEntity.Completion = 1;
                    flowTaskOperatorEntity.HandleStatus = 0;
                    flowTaskOperatorEntity.HandleTime = DateTime.Now;
                    await flowTaskOperatorBll.Update(flowTaskOperatorEntity);
                    #endregion

                    #region 更新节点
                    flowTaskNodeEntity.Completion = -1;
                    await flowTaskNodeBll.Update(flowTaskNodeEntity);
                    #endregion

                    #region 更新实例
                    if (flowTaskNodeEntity.NodeUp == "0")
                    {
                        flowTaskEntity.ThisStepId = upNodeModel.nodeId;
                        flowTaskEntity.ThisStep = "开始";
                        flowTaskEntity.Completion = 0;
                        flowTaskEntity.Status = FlowTaskStatusEnum.Reject;
                        await service.Update(flowTaskEntity);
                        await TaskNodeUpdateStateByTaskId(flowTaskEntity.Id, "-1");
                        await TaskOperatorUpdateStateByTaskId(flowTaskEntity.Id, "-1");
                    }
                    else 
                    {
                        if(flowTaskNodeEntity.NodeUp != "1")
                        {
                            upNodeEntity = flowTaskNodeEntityList.Find(m => m.NodeCode == nodeModel.rejectStep);
                            upNodeModel = upNodeEntity.NodePropertyJson.ToObject<ChildNodeModelList>();
                        }
                        //上一步是加签
                        if (upNodeModel.assigneeType == (int)FlowTaskOperatorEnum.FreeApprover)
                        {
                            var upNode = upNodeEntity;
                            //获取加签上一步节点
                            upNodeEntity = flowTaskNodeEntityList.Find(x => x.NodeNext == upNode.NodeCode);
                            flowTaskEntity.ThisStep = upNodeEntity.NodeName;
                            flowTaskEntity.ThisStepId = upNodeEntity.NodeCode;
                            //赋值加签上一步节点属性
                            upNodeModel = upNodeEntity.NodePropertyJson.ToObject<ChildNodeModelList>();
                            if (upNodeModel.progress.IsEmpty())
                            {
                                flowTaskEntity.Completion = null;
                            }
                            else
                            {
                                flowTaskEntity.Completion = Convert.ToInt32(upNodeModel.progress);
                            }
                        }
                        else
                        {
                            //上一步不是加签
                            flowTaskEntity.ThisStep = upNodeEntity.NodeName;
                            flowTaskEntity.ThisStepId = upNodeEntity.NodeCode;
                            if (upNodeModel.progress.IsEmpty())
                            {
                                flowTaskEntity.Completion = null;
                            }
                            else
                            {
                                flowTaskEntity.Completion = Convert.ToInt32(upNodeModel.progress);
                            }
                        }
                        flowTaskEntity.Status = FlowTaskStatusEnum.Handle;
                        if ("start".Equals(upNodeEntity.NodeType))
                        {
                            flowTaskEntity.Completion = 0;
                            flowTaskEntity.Status = FlowTaskStatusEnum.Draft;
                            await TaskNodeUpdateStateByTaskId(flowTaskEntity.Id, "-1");
                            await TaskOperatorUpdateStateByTaskId(flowTaskEntity.Id, "-1");
                        }
                        await service.Update(flowTaskEntity);
                    }
                    #endregion

                    #region 创建经办
                    if (flowTaskNodeEntity.NodeUp =="1")
                    {
                        var creatorUserEntity = userAllModel.Find(x => x.Id.Equals(flowTaskEntity.CreatorUserId));
                        //发起者主管
                        if (upNodeModel.assigneeType == (int)FlowTaskOperatorEnum.LaunchCharge)
                        {
                            flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                            {
                                Id = CommonHelper.Guid,
                                HandleType = ((int)FlowTaskOperatorEnum.LaunchCharge).ToString(),
                                HandleId = creatorUserEntity.ManagerId,
                                NodeCode = upNodeModel.nodeId,
                                NodeName = upNodeModel.title,
                                TaskNodeId = upNodeModel.taskNodeId,
                                TaskId = upNodeModel.taskId,
                                CreatorTime = DateTime.Now,
                                Completion = 0,
                                State = "0",
                                Type = upNodeModel.assigneeType.ToString()
                            });
                        }
                        //发起者部门主管
                        if (upNodeModel.assigneeType == (int)FlowTaskOperatorEnum.DepartmentCharge)
                        {
                            var organizeEntity = await organizeBll.GetInfo(userInfo.OrganizeId);
                            flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                            {
                                Id = CommonHelper.Guid,
                                HandleType = ((int)FlowTaskOperatorEnum.DepartmentCharge).ToString(),
                                HandleId = organizeEntity.ManagerId,
                                NodeCode = upNodeModel.nodeId,
                                NodeName = upNodeModel.title,
                                TaskNodeId = upNodeModel.taskNodeId,
                                TaskId = upNodeModel.taskId,
                                CreatorTime = DateTime.Now,
                                Completion = 0,
                                State = "0",
                                Type = upNodeModel.assigneeType.ToString()
                            });
                        }
                        //得到【指定用户】
                        if (upNodeModel.approvers != null)
                        {
                            foreach (var userId in upNodeModel.approvers)
                            {
                                flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                                {
                                    Id = CommonHelper.Guid,
                                    HandleType = ((int)FlowTaskOperatorEnum.AppointUser).ToString(),
                                    HandleId = userId,
                                    NodeCode = upNodeModel.nodeId,
                                    NodeName = upNodeModel.title,
                                    TaskNodeId = upNodeModel.taskNodeId,
                                    TaskId = upNodeModel.taskId,
                                    CreatorTime = DateTime.Now,
                                    Completion = 0,
                                    State = "0",
                                    Type = upNodeModel.assigneeType.ToString()
                                });
                            }
                        }
                        //得到【指定岗位】
                        if (upNodeModel.approverPos != null)
                        {
                            foreach (var positionId in upNodeModel.approverPos)
                            {
                                List<string> userPosition = userAllModel.FindAll(x => x.PositionId.Contains(positionId)).Select(x => x.Id).ToList();
                                getApproverUser(userPosition, flowTaskOperatorEntityList, upNodeModel);
                            }
                        }
                        //发起者本人
                        if (upNodeModel.assigneeType == (int)FlowTaskOperatorEnum.InitiatorMe)
                        {
                            flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                            {
                                Id = CommonHelper.Guid,
                                HandleType = ((int)FlowTaskOperatorEnum.InitiatorMe).ToString(),
                                HandleId = flowTaskEntity.CreatorUserId,
                                NodeCode = upNodeModel.nodeId,
                                NodeName = upNodeModel.title,
                                TaskNodeId = upNodeModel.taskNodeId,
                                TaskId = upNodeModel.taskId,
                                CreatorTime = DateTime.Now,
                                Completion = 0,
                                State = "0",
                                Type = upNodeModel.assigneeType.ToString()
                            });
                        }
                        await flowTaskOperatorBll.Create(flowTaskOperatorEntityList);
                    }
                    else if (flowTaskNodeEntity.NodeUp == "0")
                    {

                    }
                    else
                    {
                        //驳回指定节点
                        var assignFlowTaskNodeEntity = flowTaskNodeEntityList.Find(m => m.NodeCode == nodeModel.rejectStep);
                        //驳回指定节点属性
                        var assignNodeModel = assignFlowTaskNodeEntity.NodePropertyJson.ToObject<ChildNodeModelList>();
                        GetFlowTaskOperatorEntityByProperties(flowTaskOperatorEntityList, assignNodeModel, flowTaskEntity, flowHandleModel.freeApproverUserId);
                        await flowTaskOperatorBll.Create(flowTaskOperatorEntityList);
                    }
                    
                    #endregion

                    //驳回事件
                    if (nodeModel.hasApproverfunc)
                    {
                        string faceUrl = nodeModel.approverInterfaceUrl + "?" + taskNodeId + "=" + flowTaskNodeEntity.Id + "&" + handleStatus + "=" + flowTaskOperatorRecordEntity.HandleStatus;

                        if (nodeModel.approverInterfaceUrl.Contains("https"))
                        {
                            WebHelper.HttpWebRequest(faceUrl);
                        }
                        else
                        {
                            WebHelper.HttpWebRequest(faceUrl);
                        }
                    }

                    #region 消息提醒
                    Dictionary<string, object> message = new Dictionary<string, object>();
                    message["type"] = FlowMessageEnum.wait;
                    message["id"] = flowTaskEntity.Id;
                    //审核提醒
                    await MessagePush(flowTaskOperatorEntityList, flowTaskEntity.FullName + "【审核】", message.ToJson());
                    //创建者消息提醒
                    List<string> userIdList = new List<string>();
                    userIdList.Add(flowTaskEntity.CreatorUserId);
                    message["type"] = FlowMessageEnum.me;
                    await messageBll.SentMessage(userIdList, flowTaskEntity.FullName + "【审核通过】", message.ToJson());
                    #endregion

                    scope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 召回（已办事宜）
        /// </summary>
        /// <param name="flowTaskEntity">流程实例</param>
        /// <param name="flowTaskNodeEntity">流程节点</param>
        /// <param name="flowTaskOperatorRecordEntity">经办记录</param>
        /// <param name="nodeId">销回节点Id</param>
        public async Task Recall(FlowTaskEntity flowTaskEntity, FlowTaskNodeEntity flowTaskNodeEntity, FlowTaskOperatorRecordEntity flowTaskOperatorRecordEntity, string nodeId)
        {
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    var flowTaskOperatorRecordEntityList = await flowTaskOperatorRecordBll.GetList(flowTaskEntity.Id);
                    var flowTaskOperatorEntityList = await flowTaskOperatorBll.GetList(flowTaskEntity.Id);
                    var resultOperatorEntityList=new List<FlowTaskOperatorEntity>();
                    #region 之前经办
                    var beforeOperatorEntityList = flowTaskOperatorRecordEntityList.FindAll(x => x.HandleStatus == 1 && !x.NodeCode.Equals(flowTaskOperatorRecordEntity.NodeCode));
                    //去重
                    beforeOperatorEntityList= beforeOperatorEntityList.Where((x, y) => beforeOperatorEntityList.FindIndex(n => (n.NodeCode == x.NodeCode && n.HandleId == x.HandleId)) == y).ToList();
                    foreach (var item in beforeOperatorEntityList)
                    {
                        var entity = flowTaskOperatorEntityList.Find(x => x.Id == item.TaskOperatorId);
                        entity.Id = CommonHelper.Guid;
                        resultOperatorEntityList.Add(entity);
                    }
                    #endregion
                    #region 当前经办
                    var thisOperatorEntityList= flowTaskOperatorEntityList.FindAll(x => x.NodeCode.Equals(flowTaskOperatorRecordEntity.NodeCode));
                    //去重
                    thisOperatorEntityList = thisOperatorEntityList.Where((x, y) => thisOperatorEntityList.FindIndex(n => (n.NodeCode == x.NodeCode && n.HandleId == x.HandleId)) == y).ToList();
                    foreach (var item in thisOperatorEntityList)
                    {
                        var entity = item;
                        entity.Id = CommonHelper.Guid;
                        entity.HandleStatus = null;
                        entity.HandleTime = null;
                        entity.Completion = 0;
                        resultOperatorEntityList.Add(entity);
                    }
                    #endregion

                    #region 撤回数据
                    //删除经办
                    await flowTaskOperatorBll.DeleteByTaskId(flowTaskEntity.Id);
                    //删除传阅
                    await flowTaskCirculateBll.DeleteByNodeId(nodeId);
                    #endregion

                    #region 更改记录
                    flowTaskOperatorRecordEntity.TaskOperatorId = null;
                    flowTaskOperatorRecordEntity.TaskNodeId = null;
                    await flowTaskOperatorRecordBll.Update(flowTaskOperatorRecordEntity.Id, flowTaskOperatorRecordEntity);
                    #endregion

                    #region 更新经办
                    await flowTaskOperatorBll.Create(resultOperatorEntityList);
                    //flowTaskOperatorEntity.Completion = 0;
                    //flowTaskOperatorEntity.HandleStatus = null;
                    //flowTaskOperatorEntity.HandleTime = null;
                    //await flowTaskOperatorBll.Update(flowTaskOperatorEntity);
                    #endregion

                    #region 更新节点
                    flowTaskNodeEntity.Completion = 0;
                    await flowTaskNodeBll.Update(flowTaskNodeEntity);
                    #endregion

                    #region 更新实例
                    flowTaskEntity.ThisStepId = flowTaskNodeEntity.NodeCode;
                    flowTaskEntity.ThisStep = flowTaskNodeEntity.NodeName;
                    flowTaskEntity.Completion = 0;
                    flowTaskEntity.Status = FlowTaskStatusEnum.Handle;
                    await service.Update(flowTaskEntity);
                    #endregion

                    #region 召回记录
                    var userInfo = UserProvider.Instance.Get();
                    flowTaskOperatorRecordEntity.HandleId = userInfo.UserId;
                    flowTaskOperatorRecordEntity.HandleTime = DateTime.Now;
                    flowTaskOperatorRecordEntity.HandleStatus = 3;
                    flowTaskOperatorRecordEntity.NodeName = flowTaskEntity.ThisStep;
                    flowTaskOperatorRecordEntity.TaskId = flowTaskEntity.Id;
                    await flowTaskOperatorRecordBll.Create(flowTaskOperatorRecordEntity);
                    #endregion

                    scope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 终止
        /// </summary>
        /// <param name="flowTaskEntity">流程实例</param>
        /// <param name="flowHandleModel">流程经办</param>
        public async Task Cancel(FlowTaskEntity flowTaskEntity, FlowHandleModel flowHandleModel)
        {
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    #region 更新实例
                    flowTaskEntity.Status = FlowTaskStatusEnum.Cancel;
                    flowTaskEntity.EndTime = DateTime.Now;
                    await service.Update(flowTaskEntity);
                    #endregion

                    #region 作废记录
                    var userInfo = UserProvider.Instance.Get();
                    FlowTaskOperatorRecordEntity flowTaskOperatorRecordEntity = new FlowTaskOperatorRecordEntity();
                    flowTaskOperatorRecordEntity.HandleOpinion = flowHandleModel.handleOpinion;
                    flowTaskOperatorRecordEntity.HandleId = userInfo.UserId;
                    flowTaskOperatorRecordEntity.HandleTime = DateTime.Now;
                    flowTaskOperatorRecordEntity.HandleStatus = 4;
                    flowTaskOperatorRecordEntity.NodeName = flowTaskEntity.ThisStep;
                    flowTaskOperatorRecordEntity.TaskId = flowTaskEntity.Id;
                    await flowTaskOperatorRecordBll.Create(flowTaskOperatorRecordEntity);
                    #endregion

                    scope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="flowTaskEntities"></param>
        /// <returns></returns>
        public async Task Delete(List<FlowTaskEntity> flowTaskEntities)
        {
            try
            {
                flowTaskEntities.ForEach(x =>
                    service.Delete(x)
                    );
            }
            catch (Exception ex)
            {

                throw ExceptionEx.Throw(ex);
            }
        }

        #region private Method
        /// <summary>
        /// 根据连线自己找到下一个步骤节点
        /// </summary>
        /// <param name="formDataJson">表单数据Json</param>
        /// <param name="flowNodeLineList">流程连线</param>
        /// <param name="flowNodeList">流程节点</param>
        /// <param name="flowNodeModel">当前节点</param>
        /// <returns></returns>
        private string GetNextNode(string formDataJson, List<ConditionList> conditionList, List<ChildNodeModelList> modelLists, ChildNodeModelList childNodeModel, Dictionary<string, string> jnpfKey, Dictionary<string, object> keyList)
        {
            string nodeId = "";
            bool flag = false;
            bool isDefault = false;
            //有条件先进入条件判断，条件成功取条件的下一节点
            for (int i = 0; i < conditionList.Count; i++)
            {
                var condition = conditionList[i];
                if (childNodeModel.nodeId.Equals(condition.prevId))
                {
                    var conditions = condition.conditions;
                    flag = NodeConditionDecide(formDataJson, conditions, jnpfKey, keyList);
                    isDefault = condition.isDefault;
                    if (flag|| isDefault)
                    {
                        if (condition.child)
                        {
                            nodeId = condition.childNodeId;
                        }
                        else
                        {
                            nodeId = condition.firstId;
                        }
                        if (nodeId.IsEmpty())
                        {
                            flag = false;
                        }
                        if (!isDefault)
                        {
                            break;
                        }
                    }
                }
            }
            //条件没有下一节点
            if (!flag&&!isDefault)
            {
                //不是外层的下一节点
                if (!"0".Equals(childNodeModel.num))
                {
                    nodeId = childNodeModel.firstId;
                    if (childNodeModel.child)
                    {
                        nodeId = childNodeModel.childNode;
                    }
                }
                else
                {
                    //外层的子节点
                    if (childNodeModel.child)
                    {
                        nodeId = childNodeModel.childNode;
                    }
                }
            }
            return nodeId;

        }
        /// <summary>
        /// 节点条件判断
        /// </summary>
        /// <param name="formDataJson">表单数据Json</param>
        /// <param name="conditionList">条件聚合</param>
        /// <returns></returns>
        private bool NodeConditionDecide(string formDataJson, List<ProperCondModel> conditionList, Dictionary<string, string> jnpfKey, Dictionary<string, object> keyList)
        {
            try
            {
                bool flag = false;
                var eval = new CsEvaluator();
                StringBuilder expression = new StringBuilder();
                var formData = formDataJson.ToObject();
                int i = 0;
                foreach (ProperCondModel flowNodeWhereModel in conditionList)
                {
                    var logic = flowNodeWhereModel.logic;
                    var formValue = formData[flowNodeWhereModel.field].ToString();
                    var symbol = flowNodeWhereModel.symbol.Equals("==") ? "=" : flowNodeWhereModel.symbol;
                    var value = flowNodeWhereModel.filedValue;
                    var jnpfkey = jnpfKey.ContainsKey(flowNodeWhereModel.field) ? jnpfKey[flowNodeWhereModel.field].ToString() : null;
                    if (jnpfKey.IsNotEmptyOrNull())
                    {
                        var condFiledValue = value.Trim();
                        //下拉和单选
                        if ("select".Equals(jnpfkey) || "radio".Equals(jnpfkey))
                        {
                            List<Dictionary<string, string>> dataList = keyList[flowNodeWhereModel.field].ToJson().ToList<Dictionary<string, string>>();
                            Dictionary<string, string> data = dataList.Find(x => x["id"].ToString().Equals(condFiledValue) || x["fullName"].ToString().Equals(condFiledValue));
                            if (data != null)
                            {
                                value = data["id"].ToString();
                            }
                        }
                        //公司和部门
                        if ("comSelect".Equals(jnpfkey) || "depSelect".Equals(jnpfkey))
                        {
                            List<OrganizeEntity> dataList = keyList[flowNodeWhereModel.field].ToJson().ToList<OrganizeEntity>();
                            OrganizeEntity organize = dataList.Find(x => x.Id.Equals(condFiledValue) || x.FullName.Equals(condFiledValue));
                            if (organize != null)
                            {
                                value = organize.Id;
                            }
                        }
                        //岗位
                        if ("posSelect".Equals(jnpfkey))
                        {
                            List<PositionEntity> dataList = keyList[flowNodeWhereModel.field].ToJson().ToList<PositionEntity>();
                            PositionEntity position = dataList.Find(x => x.Id.Equals(condFiledValue) || x.FullName.Equals(condFiledValue));
                            if (position != null)
                            {
                                value = position.Id;
                            }
                        }
                        //字典
                        if ("dicSelect".Equals(jnpfkey))
                        {
                            List<DictionaryTypeEntity> dictypeList = keyList[flowNodeWhereModel.field].ToJson().ToList<DictionaryTypeEntity>();
                            DictionaryTypeEntity dic = dictypeList.Find(x => x.Id.Equals(formValue));
                            if (dic != null)
                            {
                                value = dic.Id;
                            }
                        }
                        //用户
                        if ("userSelect".Equals(jnpfkey))
                        {
                            List<UserEntity> dataList = keyList[flowNodeWhereModel.field].ToJson().ToList<UserEntity>();
                            UserEntity user = dataList.Find(x => x.Id.Equals(condFiledValue) || x.RealName.Equals(condFiledValue) || x.Account.Equals(condFiledValue));
                            if (user != null)
                            {
                                value = user.Id;
                            }
                        }
                    }

                    expression.Append(string.Format("{0}{1}{2}", Asc(formValue), symbol, Asc(value)));
                    if (!string.IsNullOrEmpty(logic))
                    {
                        if (i != conditionList.Count - 1)
                        {
                            expression.Append(" " + logic.Replace("&&", " and ").Replace("||", " or ") + " ");
                        }
                    }
                    i++;
                }
                if (expression.ToString().IsNotEmptyOrNull())
                {
                    flag = (bool)new DataTable().Compute(expression.ToString(), "");
                }
                return flag;
            }
            catch (Exception e)
            {

                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// Asc码转换
        /// </summary>
        /// <param name="character"></param>
        /// <returns></returns>
        public static string Asc(string character)
        {
            StringBuilder sb = new StringBuilder();
            char[] chars = character.ToCharArray();
            foreach (var item in chars)
            {
                sb.Append((int)item);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 验证有效状态
        /// </summary>
        /// <param name="status">状态编码</param>
        /// <returns></returns>
        private bool CheckStatus(int? status)
        {
            if (status == FlowTaskStatusEnum.Draft || status == FlowTaskStatusEnum.Reject || status == FlowTaskStatusEnum.Revoke)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 消息提醒（审核提醒）
        /// </summary>
        /// <param name="data">经办用户</param>
        /// <param name="title">消息标题</param>
        /// <param name="bodyText">消息内容</param>
        public async Task MessagePush(List<FlowTaskOperatorEntity> data, string title, string bodyText = null)
        {
            if (data.Count > 0)
            {
                var toUserIds = new List<string>();
                foreach (var item in data)
                {
                    if (item.HandleType == ((int)FlowTaskOperatorEnum.AppointPosition).ToString())
                    {
                        //根据岗位找出用户列表
                        var users = await userBll.GetListByPositionId(item.HandleId);
                        toUserIds.AddRange(users.Select(m => m.Id));
                    }
                    else
                    {
                        toUserIds.Add(item.HandleId);
                    }
                }
                await messageBll.SentMessage(toUserIds, title, bodyText);
            }
        }
        /// <summary>
        /// 消息提醒（抄送提醒）
        /// </summary>
        /// <param name="data">经办用户</param>
        /// <param name="title">消息标题</param>
        /// <param name="bodyText">消息内容</param>
        private async Task MessagePushCirculate(List<FlowTaskCirculateEntity> data, string title, string bodyText = null)
        {
            if (data.Count > 0)
            {
                var toUserIds = new List<string>();
                foreach (var item in data)
                {
                    if (item.ObjectType == ((int)FlowTaskOperatorEnum.AppointPosition).ToString())
                    {
                        //根据岗位找出用户列表
                        var users = await userBll.GetListByPositionId(item.ObjectId);
                        toUserIds.AddRange(users.Select(m => m.Id));
                    }
                    else
                    {
                        toUserIds.Add(item.ObjectId);
                    }
                }
                await messageBll.SentMessage(toUserIds, title, bodyText);
            }
        }

        private void childNodeModelLists(ChildNodeModel childNodeModel, List<ChildNodeModelList> childNodeModels, List<ConditionList> conditionLists)
        {
            if (childNodeModel != null)
            {
                var child = childNodeModel.childNode != null;
                var condition = childNodeModel.conditionNodes != null;
                var childNodeModelList = childNodeModel.MapTo<ChildNodeModelList>();
                var properModel = childNodeModel.properties;
                childNodeModelList.approverPos = properModel.approverPos;
                childNodeModelList.approvers = properModel.approvers;
                childNodeModelList.rejectStep = properModel.rejectStep;
                childNodeModelList.progress = properModel.progress;
                childNodeModelList.circulatePosition = properModel.circulatePosition;
                childNodeModelList.circulateUser = properModel.circulateUser;
                childNodeModelList.assigneeType = properModel.assigneeType;
                childNodeModelList.formOperates = properModel.formOperates;
                //开始事件
                childNodeModelList.hasInitfunc = properModel.hasInitfunc;
                childNodeModelList.initInterfaceType = properModel.initInterfaceType;
                childNodeModelList.initInterfaceUrl = properModel.initInterfaceUrl;
                //结束事件
                childNodeModelList.hasEndfunc = properModel.hasEndfunc;
                childNodeModelList.endInterfaceType = properModel.endInterfaceType;
                childNodeModelList.endInterfaceUrl = properModel.endInterfaceUrl;
                //节点事件
                childNodeModelList.hasApproverfunc = properModel.hasApproverfunc;
                childNodeModelList.approverInterfaceType = properModel.approverInterfaceType;
                childNodeModelList.approverInterfaceUrl = properModel.approverInterfaceUrl;
                childNodeModelList.title = properModel.title;
                childNodeModelList.num = "0";
                childNodeModelList.firstId = "";
                childNodeModelList.child = child;
                childNodeModelList.childNode = child == true ? childNodeModel.childNode.nodeId : "";
                childNodeModels.Add(childNodeModelList);
                if (condition)
                {
                    conditionNodesList(childNodeModel, childNodeModelList.childNode, childNodeModels, conditionLists);
                }
                if (child)
                {
                    childNodeModelLists(childNodeModel.childNode, childNodeModels, conditionLists);
                }
            }
        }
        private void conditionNodesList(ChildNodeModel parentModel, string firstId, List<ChildNodeModelList> childNodeListAll, List<ConditionList> conditionListAll)
        {
            //父节点的子节点
            var childNodeModel = parentModel.childNode;
            var parentId = firstId;
            if (childNodeModel != null)
            {
                parentId = childNodeModel.nodeId;
            }
            //父节点条件集合
            var conditionList = parentModel.conditionNodes;
            for (int i = 0; i < conditionList.Count; i++)
            {
                var condModel = conditionList[i];
                //获取条件成功节点
                var model = condModel.childNode;
                var nodeId = condModel.nodeId;
                var perId = condModel.prevId;
                var child = false;
                var condition = false;
                var conditionChild = model != null;
                if (conditionChild)
                {
                    child = model.childNode != null;
                    condition = model.conditionNodes != null;
                    var childNodeModelList = model.MapTo<ChildNodeModelList>();
                    childNodeModelList.child = child;
                    childNodeModelList.num = "1";
                    childNodeModelList.childNode = child == true ? model.childNode.nodeId : "";
                    childNodeModelList.firstId = parentId;
                    propertiesList(childNodeModelList, model.properties, childNodeListAll);
                }
                //获取条件数据
                var conditions = condModel.properties.conditions;
                var conditionModel = new ConditionList();
                conditionModel.conditions = conditions;
                conditionModel.nodeId = nodeId;
                conditionModel.prevId = perId;
                conditionModel.child = conditionChild;
                conditionModel.childNodeId = conditionChild == true ? condModel.childNode.nodeId : "";
                conditionModel.firstId = parentId;
                conditionModel.isDefault = condModel.properties.isDefault;
                conditionListAll.Add(conditionModel);
                if (condition)
                {
                    conditionNodesList(model, parentId, childNodeListAll, conditionListAll);
                }
                if (child)
                {
                    conditChildOne(model, parentId, childNodeListAll, conditionListAll);
                }
            }
        }

        private void propertiesList(ChildNodeModelList childNodeModelList, ChildNodeProperModel properties, List<ChildNodeModelList> childNodeListAll)
        {
            childNodeModelList.approverPos = properties.approverPos;
            childNodeModelList.progress = properties.progress;
            childNodeModelList.approvers = properties.approvers;
            childNodeModelList.rejectStep = properties.rejectStep;
            childNodeModelList.circulatePosition = properties.circulatePosition;
            childNodeModelList.circulateUser = properties.circulateUser;
            childNodeModelList.assigneeType = properties.assigneeType;
            childNodeModelList.title = properties.title;
            //开始事件
            childNodeModelList.hasInitfunc = properties.hasInitfunc;
            childNodeModelList.initInterfaceType = properties.initInterfaceType;
            childNodeModelList.initInterfaceUrl = properties.initInterfaceUrl;
            //结束事件
            childNodeModelList.hasEndfunc = properties.hasEndfunc;
            childNodeModelList.endInterfaceType = properties.endInterfaceType;
            childNodeModelList.endInterfaceUrl = properties.endInterfaceUrl;
            //节点事件
            childNodeModelList.hasApproverfunc = properties.hasApproverfunc;
            childNodeModelList.approverInterfaceType = properties.approverInterfaceType;
            childNodeModelList.approverInterfaceUrl = properties.approverInterfaceUrl;
            childNodeListAll.Add(childNodeModelList);
        }

        private void conditChildOne(ChildNodeModel parentModel, String firstId, List<ChildNodeModelList> childNodeListAll, List<ConditionList> conditionListAll)
        {
            var childNodeModel = parentModel.childNode;
            if (childNodeModel != null)
            {
                var child = childNodeModel.childNode != null;
                var condition = childNodeModel.conditionNodes != null;
                var properModel = childNodeModel.properties;
                var childNodeModelList = childNodeModel.MapTo<ChildNodeModelList>();
                childNodeModelList.approverPos = properModel.approverPos;
                childNodeModelList.approvers = properModel.approvers;
                childNodeModelList.rejectStep = properModel.rejectStep;
                childNodeModelList.progress = properModel.progress;
                childNodeModelList.circulatePosition = properModel.circulatePosition;
                childNodeModelList.circulateUser = properModel.circulateUser;
                childNodeModelList.assigneeType = properModel.assigneeType;
                childNodeModelList.formOperates = properModel.formOperates;
                childNodeModelList.title = properModel.title;
                childNodeModelList.num = "1";
                childNodeModelList.child = child;
                childNodeModelList.childNode = child == true ? childNodeModel.childNode.nodeId : "";
                childNodeModelList.firstId = firstId;
                childNodeListAll.Add(childNodeModelList);
                if (condition)
                {
                    this.conditionNodesList(childNodeModel, firstId, childNodeListAll, conditionListAll);
                }
                if (child)
                {
                    this.conditChildOne(childNodeModel, firstId, childNodeListAll, conditionListAll);
                }
            }
        }

        private async Task UpdateReject(string taskId, string type)
        {
            var flowTaskOperatorList = await flowTaskOperatorBll.GetList(taskId);
            flowTaskOperatorList.ForEach(x => { x.Type = type; x.Completion = 1; });
            foreach (var item in flowTaskOperatorList)
            {
                await flowTaskOperatorBll.Update(item);
            }
        }
        //更新状态(节点)
        private async Task TaskNodeUpdateStateByTaskId(string taskId, string state)
        {
            var flowTaskNodeList = await flowTaskNodeBll.GetList(taskId);
            flowTaskNodeList.ForEach(x => { x.State = state; });
            foreach (var item in flowTaskNodeList)
            {
                await flowTaskNodeBll.Update(item);
            }
        }

        //更新状态（经办）
        private async Task TaskOperatorUpdateStateByTaskId(string taskId, string state)
        {
            var flowTaskOperatorList = await flowTaskOperatorBll.GetList(taskId);
            flowTaskOperatorList.ForEach(x => { x.State = state; });
            foreach (var item in flowTaskOperatorList)
            {
                await flowTaskOperatorBll.Update(item);
            }
        }

        /// <summary>
        /// 封装属性key和保存list
        /// </summary>
        /// <param name="fieLdsModelList"></param>
        /// <param name="jnpfKey"></param>
        /// <param name="keyList"></param>
        private async Task tempJson(List<FieldsModel> fieLdsModelList, Dictionary<string, string> jnpfKey, Dictionary<string, object> keyList)
        {
            List<DictionaryDataEntity> dicDatayList = await dictionaryDataBll.GetList();
            List<OrganizeEntity> organizeList = await organizeBll.GetList();
            List<UserEntity> userList = await userBll.GetList();
            List<PositionEntity> positionList = await positionBll.GetList();
            List<DictionaryTypeEntity> dictypeList = await dictionaryTypeBll.GetList();
            foreach (var fieLdsModel in fieLdsModelList)
            {
                string model = fieLdsModel.__vModel__;
                Models.VisualDev.ConfigModel config = fieLdsModel.__config__;
                string key = config.jnpfKey;
                if (model.IsNotEmptyOrNull())
                {
                    jnpfKey.Add(model, key);
                }
                if ("select".Equals(key) || "checkbox".Equals(key) || "radio".Equals(key))
                {
                    string type = config.dataType;
                    List<Dictionary<string, string>> optionslList = new List<Dictionary<string, string>>();
                    string fullName = config.props.label;
                    string value = config.props.value;
                    if ("dictionary".Equals(type))
                    {
                        string dictionaryType = config.dictionaryType;
                        List<DictionaryDataEntity> dicList = dicDatayList.FindAll(x => x.DictionaryTypeId.Equals(dictionaryType));
                        foreach (DictionaryDataEntity dataEntity in dicList)
                        {
                            Dictionary<string, string> optionsModel = new Dictionary<string, string>();
                            optionsModel.Add("id", dataEntity.Id);
                            optionsModel.Add("fullName", dataEntity.FullName);
                            optionslList.Add(optionsModel);
                        }
                    }
                    else if ("static".Equals(type))
                    {
                        List<Dictionary<string, object>> staticList = fieLdsModel.__slot__.options.ToJson().ToList<Dictionary<string, object>>();
                        foreach (Dictionary<string, object> options in staticList)
                        {
                            Dictionary<string, string> optionsModel = new Dictionary<string, string>();
                            optionsModel.Add("id", options["id"].ToString());
                            optionsModel.Add("fullName", options["fullName"].ToString());
                            optionslList.Add(optionsModel);
                        }
                    }
                    else if ("dynamic".Equals(type))
                    {
                        string dynId = config.propsUrl;
                        //查询外部接口
                        Dictionary<string, object> dynamicMap = new Dictionary<string, object>();
                        dynamicMap.Add("data", await dataInterfaceBll.GetData(dynId));
                        if (dynamicMap["data"] != null)
                        {
                            List<Dictionary<string, object>> dataList = dynamicMap["data"].ToJson().ToList<Dictionary<string, object>>();
                            foreach (Dictionary<string, object> options in dataList)
                            {
                                Dictionary<string, string> optionsModel = new Dictionary<string, string>();
                                optionsModel.Add("id", options[value].ToString());
                                optionsModel.Add("fullName", options[fullName].ToString());
                                optionslList.Add(optionsModel);
                            }
                        }
                    }
                    keyList.Add(model, optionslList);
                }
            }
        }

        /// <summary>
        /// 判断经办岗位是否存在指定用户
        /// </summary>
        /// <param name="userPosition"></param>
        /// <param name="flowTaskOperatorEntityList"></param>
        /// <param name="nextNodeModel"></param>
        private void getApproverUser(List<string> userPosition, List<FlowTaskOperatorEntity> flowTaskOperatorEntityList, ChildNodeModelList nextNodeModel)
        {
            foreach (var user in userPosition)
            {
                // 判断是否有添加这个人
                if (flowTaskOperatorEntityList.FindAll(x => x.HandleId.Equals(user)).Count == 0)
                {
                    FlowTaskOperatorEntity flowTask = new FlowTaskOperatorEntity();
                    flowTask.Id = CommonHelper.Guid;
                    flowTask.HandleType = ((int)FlowTaskOperatorEnum.AppointUser).ToString();
                    flowTask.HandleId = user;
                    flowTask.NodeCode = nextNodeModel.nodeId;
                    flowTask.NodeName = nextNodeModel.title;
                    flowTask.TaskNodeId = nextNodeModel.taskNodeId;
                    flowTask.TaskId = nextNodeModel.taskId;
                    flowTask.CreatorTime = DateTime.Now;
                    flowTask.Completion = 0;
                    flowTask.State = "0";
                    flowTask.Type = nextNodeModel.assigneeType.ToString();
                    flowTaskOperatorEntityList.Add(flowTask);
                }
            }
        }

        /// <summary>
        /// 判断传阅用户是否在添加岗位上
        /// </summary>
        /// <param name="circulatePosition"></param>
        /// <param name="positionIds"></param>
        /// <returns></returns>
        private bool getCirculateUser(List<string> circulatePosition, List<string> positionIds)
        {
            bool flag = true;
            foreach (var positionId in circulatePosition)
            {
                if (positionIds.FindAll(x => x.Contains(positionId)).Count > 0)
                {
                    flag = false;
                    break;
                }
            }
            return flag;
        }

        /// <summary>
        /// 根据节点属性创建流程经办实体
        /// </summary>
        /// <param name="flowTaskOperatorEntityList">接收参数</param>
        /// <param name="nextNodeModel">属性对象</param>
        /// <param name="flowTaskEntity">流程任务实体</param>
        /// <param name="freeApproverUserId">加签人</param>
        private void GetFlowTaskOperatorEntityByProperties(List<FlowTaskOperatorEntity> flowTaskOperatorEntityList, ChildNodeModelList nextNodeModel, FlowTaskEntity flowTaskEntity,string freeApproverUserId)
        {
            var userAllModel = userBll.GetList().Result;
            var createUser = userAllModel.Find(x => x.Id.Equals(flowTaskEntity.CreatorUserId));
            //发起者【发起主管】
            if (nextNodeModel.assigneeType == (int)FlowTaskOperatorEnum.LaunchCharge)
            {
                flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                {
                    Id = CommonHelper.Guid,
                    HandleType = ((int)FlowTaskOperatorEnum.LaunchCharge).ToString(),
                    HandleId = createUser.ManagerId,
                    NodeCode = nextNodeModel.nodeId,
                    NodeName = nextNodeModel.title,
                    TaskNodeId = nextNodeModel.taskNodeId,
                    TaskId = nextNodeModel.taskId,
                    CreatorTime = DateTime.Now,
                    Completion = 0,
                    State = "0",
                    Type = nextNodeModel.assigneeType.ToString()
                });
            }
            //发起者【部门主管】
            if (nextNodeModel.assigneeType == (int)FlowTaskOperatorEnum.DepartmentCharge)
            {
                var organizeEntity = organizeBll.GetInfo(createUser.OrganizeId).Result;
                flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                {
                    Id = CommonHelper.Guid,
                    HandleType = ((int)FlowTaskOperatorEnum.DepartmentCharge).ToString(),
                    HandleId = organizeEntity.ManagerId,
                    NodeCode = nextNodeModel.nodeId,
                    NodeName = nextNodeModel.title,
                    TaskNodeId = nextNodeModel.taskNodeId,
                    TaskId = nextNodeModel.taskId,
                    CreatorTime = DateTime.Now,
                    Completion = 0,
                    State = "0",
                    Type = nextNodeModel.assigneeType.ToString()
                });
            }
            //发起者【发起本人】
            if (nextNodeModel.assigneeType == (int)FlowTaskOperatorEnum.InitiatorMe)
            {
                flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                {
                    Id = CommonHelper.Guid,
                    HandleType = ((int)FlowTaskOperatorEnum.InitiatorMe).ToString(),
                    HandleId = flowTaskEntity.CreatorUserId,
                    NodeCode = nextNodeModel.nodeId,
                    NodeName = nextNodeModel.title,
                    TaskNodeId = nextNodeModel.taskNodeId,
                    TaskId = nextNodeModel.taskId,
                    CreatorTime = DateTime.Now,
                    Completion = 0,
                    State = "0",
                    Type = nextNodeModel.assigneeType.ToString()
                });
            }
            //得到【授权审批人】
            if (nextNodeModel.assigneeType == (int)FlowTaskOperatorEnum.FreeApprover)
            {
                if (string.IsNullOrEmpty(freeApproverUserId))
                    throw new Exception("未找到授权审批人");
                flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                {
                    Id = CommonHelper.Guid,
                    HandleType = ((int)FlowTaskOperatorEnum.FreeApprover).ToString(),
                    HandleId = freeApproverUserId,
                    NodeCode = nextNodeModel.nodeId,
                    NodeName = nextNodeModel.title,
                    TaskNodeId = nextNodeModel.taskNodeId,
                    TaskId = nextNodeModel.taskId,
                    CreatorTime = DateTime.Now,
                    Completion = 0,
                    State = "0",
                    Type = nextNodeModel.assigneeType.ToString()
                });
            }
            //得到【指定用户】
            if (nextNodeModel.approvers != null)
            {
                foreach (var userId in nextNodeModel.approvers)
                {
                    flowTaskOperatorEntityList.Add(new FlowTaskOperatorEntity()
                    {
                        Id = CommonHelper.Guid,
                        HandleType = ((int)FlowTaskOperatorEnum.AppointUser).ToString(),
                        HandleId = userId,
                        NodeCode = nextNodeModel.nodeId,
                        NodeName = nextNodeModel.title,
                        TaskNodeId = nextNodeModel.taskNodeId,
                        TaskId = nextNodeModel.taskId,
                        CreatorTime = DateTime.Now,
                        Completion = 0,
                        State = "0",
                        Type = nextNodeModel.assigneeType.ToString()
                    });
                }
            }
            //得到【指定岗位】
            if (nextNodeModel.approverPos != null)
            {
                foreach (var positionId in nextNodeModel.approverPos)
                {
                    var userPosition = userAllModel.FindAll(x => x.PositionId.Contains(positionId)).Select(x => x.Id).ToList<string>();
                    getApproverUser(userPosition, flowTaskOperatorEntityList, nextNodeModel);
                }
            }
            
        }



        #endregion

        #region 新函数
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">流程任务主键</param>
        /// <param name="flowId">引擎id</param>
        /// <param name="processId">实例进程id</param>
        /// <param name="flowTitle">任务标题</param>
        /// <param name="flowUrgent">紧急程度</param>
        /// <param name="billNo">流水号</param>
        /// <param name="formEntity">引擎表单数据json</param>
        /// <param name="freeApproverUserId">加签人</param>
        /// <returns></returns>
        public async Task Submit_New(string id, string flowId, string processId, string flowTitle, int? flowUrgent, string billNo, object formEntity, string freeApproverUserId = "")
        {
            try
            {
                #region 初始化对象
                var userInfo = UserProvider.Instance.Get();
                var userAllModel = await userBll.GetList();
                //流程引擎
                var flowEngineEntity = await flowEngineBll.GetInfo(flowId);
                //流程实例
                var flowTaskEntity = new FlowTaskEntity();
                //流程节点
                var flowTaskNodeEntityList = new List<FlowTaskNodeEntity>();
                //流程经办
                var flowTaskOperatorEntityList = new List<FlowTaskOperatorEntity>();
                //流程传阅
                var flowTaskCirculateEntityList = new List<FlowTaskCirculateEntity>();
                #endregion

            }
            catch (Exception ex)
            {
                LogFactory.GetLogger().Error("Submit_New函数错误：" + ex);
                throw;
            }
        }

        public void GetFlowTemplateAll(FlowTemplateJsonModel flowTemplateJsonModel, List<ChildNodeModelList> childNodeModelLists)
        {
            if (flowTemplateJsonModel.IsNotEmptyOrNull())
            {
                var childNodeModel = flowTemplateJsonModel.properties.ToObject<ChildNodeModelList>();
                childNodeModel.type = flowTemplateJsonModel.type;
                childNodeModel.nodeId = flowTemplateJsonModel.nodeId;
                childNodeModel.prevId = flowTemplateJsonModel.prevId;
                childNodeModelLists.Add(childNodeModel);
                var haschildNode = flowTemplateJsonModel.childNode.IsNotEmptyOrNull();
                var hasconditionNodes = flowTemplateJsonModel.conditionNodes.IsNotEmptyOrNull() && flowTemplateJsonModel.conditionNodes.Count > 0;
                if (hasconditionNodes)
                {
                    foreach (var conditionNode in flowTemplateJsonModel.conditionNodes)
                    {
                        GetFlowTemplateAll(conditionNode, childNodeModelLists);
                    }
                }
                if (haschildNode)
                {
                    GetFlowTemplateAll(flowTemplateJsonModel.childNode, childNodeModelLists);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="childNodeModelOld">源数据</param>
        /// <param name="childNodeModelNew">实际节点数据</param>
        /// <param name="prevId">上级节点</param>
        /// <param name="jnpfKey"></param>
        /// <param name="keyList"></param>
        public void GetChildNodeList(List<ChildNodeModelList> childNodeModelOld, List<ChildNodeModelList> childNodeModelNew, string prevId, Dictionary<string, string> jnpfKey, Dictionary<string, object> keyList)
        {
            var lastNodeId = "";
            if (true)
            {

            }
            var childNodeModelList = childNodeModelOld.FindAll(x => x.prevId == prevId);
            var conditionFlag = false;
            foreach (var item in childNodeModelList)
            {
                if (item.type == "condition")
                {
                    //执行条件成功将conditionFlag改为true

                    //添加数据
                    var conditionChildNodeModelList = childNodeModelOld.FindAll(x => x.prevId == item.nodeId);
                    if (conditionChildNodeModelList.Count == 1)
                    {
                        var conditionChildNodeModel = conditionChildNodeModelList[0];
                        conditionChildNodeModel.prevId = item.prevId;
                        childNodeModelNew.Add(item);
                        GetChildNodeList(childNodeModelOld, childNodeModelNew, conditionChildNodeModel.nodeId, jnpfKey, keyList);
                    }
                    else
                    {
                        if (conditionChildNodeModelList[0].type == "approver")
                        {
                            conditionChildNodeModelList.ForEach(x => x.prevId = item.prevId);
                            childNodeModelNew.Add(item);
                        }
                        else
                        {

                        }
                    }
                }
                //最终节点
                if (item.type == "approver" && !conditionFlag)
                {
                    childNodeModelNew.Add(item);
                    GetChildNodeList(childNodeModelOld, childNodeModelNew, item.nodeId, jnpfKey, keyList);
                }
            }
        }

        private void childNodeModelListsNew(FlowTemplateJsonModel flowTemplateJsonModel, List<ChildNodeModelList> childNodeModels, List<ConditionList> conditionLists)
        {
            if (flowTemplateJsonModel.IsNotEmptyOrNull())
            {
                #region 发起节点
                childNodeModels.Add(new ChildNodeModelList()
                {
                    type = flowTemplateJsonModel.type,
                    nodeId = flowTemplateJsonModel.nodeId,

                });
                #endregion
                //是否存在子节点或条件
                var childFlag = flowTemplateJsonModel.childNode.IsNotEmptyOrNull();
                var conditionFlag = flowTemplateJsonModel.conditionNodes.IsNotEmptyOrNull() && flowTemplateJsonModel.conditionNodes.Count > 0;

            }
        }
        #endregion
    }
}